<template>
  <div>
  <base-modal
    :show.sync="visible"
    :title="$t('common.base.statistics')"
    width="1000px"
    class="statistical-dialog"
    @closed="onClose('form')"
  >
    <div class="base-modal-content">
      <div class="statistical-search">
        <div class="search-left">
          <el-select v-model="form.taskTimeTypeEnum" :placeholder="$t('common.placeholder.select')">
            <el-option :label="$t('task.setting.taskAdditionalSetting.taskFinishTime')" value="success"></el-option>
            <el-option :label="$t('task.setting.taskAdditionalSetting.taskCreateTime')" value="create"></el-option>
          </el-select>
          <el-date-picker
            v-model="timeArrRange"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            @change="onTimeChange"
          >
          </el-date-picker>
          <el-input v-model="form.searchKey" :placeholder="$t('task.tip.taskAdditionalTip3')"></el-input>
          <el-button type="primary" @click="onSearch">{{$t('common.base.search')}}</el-button>
        </div>
        <div class="search-right" v-if="isButtonDisplayed">       
          <a v-if="useExportUrl" :href="`${exportUrl}/outside/pc/inventory/exportTaskInventory?cardId=${card.id}&inventoryTypeEnum=${form.inventoryTypeEnum}&taskTimeTypeEnum=${form.taskTimeTypeEnum}&startDate=${form.startDate}&endDate=${form.endDate}&searchKey=${form.searchKey}`">{{$t('common.base.export')}}</a>
          <a v-else @click="OpenExport">{{$t('common.base.export')}}</a>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        class="page-table statistical-table"
        :highlight-current-row="false"
        border
        header-row-class-name="page-table-header" 
        stripe
        tooltip-effect="dark"
        v-loading="loading">
        <el-table-column  
          v-for="(column, index) in columns" 
          :key="`${column.field}_${index}`"
          :prop="column.fieldName" 
          :label="column.displayName"
          :show-overflow-tooltip="true"
          :min-width="column.minWidth || '120px'">
          <template slot-scope="scope">
            <!-- 工单编号 -->
            <template v-if="column.fieldName === 'taskNo'">
              <a @click="openTaskView(scope.row.taskId, scope.row.taskNo)">{{scope.row.taskNo}}</a>
            </template>

            <!-- start 单价 -->
            <template v-else-if="column.fieldName === 'salePrice' && card.specialfrom !='备件清单'">
              {{ scope.row | fmt_salePrice_currency }} 
            </template>
            <!-- end 单价 -->
            
             <!-- 小计 -->
            <template v-else-if="column.fieldName === 'total'">
              {{scope.row.salePrice && (scope.row.preNum * scope.row.salePrice).toFixed(2)}}<span v-if="internationalGray && card.specialfrom !='备件清单'" class="ml-3">{{scope.row.salePriceCurrency || 'CNY'}}</span>
            </template>

            <!-- 协同人 -->
            <template v-else-if="column.fieldName === 'synergies'">
               <p v-if="scope.row[column.fieldName] && scope.row[column.fieldName].length">{{fmt_synergies(scope.row[column.fieldName])}}</p>
            </template>
            
            <template v-else>
              {{scope.row[column.fieldName]}}
            </template>
          </template>
        </el-table-column>

      </el-table>
      <div class="table-footer comment-list-table-footer">
        <div class="comment-list-table-footer-info task-flex task-ai">
          <i18n path="common.base.table.totalPiece">
            <span place="count" class="level-padding">{{totalElements || 0}}</span>
          </i18n>
          <div class="task-font14 task-c6 task-ml12">
            <i18n path="task.setting.taskAdditionalSetting.eachPageNum">
              <el-select
                place="count"
                v-model="form.pageSize"
                :placeholder="$t('common.placeholder.select')"
                @change="handleSizeChange(form.pageSize)"
                class="table-footer-select"
              >
                <el-option :label="10" :value="10"></el-option>
                <el-option :label="20" :value="20"></el-option>
                <el-option :label="50" :value="50"></el-option>
              </el-select>
            </i18n>
          </div>
        </div>
        <el-pagination
          v-if="this.tableData"
          class="comment-list-table-footer-pagination"
          background
          @current-change="jumpPage"
          @size-change="handleSizeChange"
          :page-size="form.pageSize"
          :current-page="form.pageNum"
          layout="prev, pager, next, jumper"
          :total="totalElements"
        >
        </el-pagination>
      </div>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onClose" >{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
  <!-- start 导出s -->
  <base-export-group
      ref="exportRef"
      :alert="exportAlert"

      :columns="exportColumn"
      :build-params="exportParamsBuild"

      :group="true"
      :validate="exportCountCheck"
      method="post"
      action="/excels/card/taskCardExport"
    />
    <!-- end 导出e -->
</div> 
</template>
<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
// util
import { formatDate, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import fieldUtil from './cardField';
import { checkButtonDisplayed } from '@src/util/dom';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
import i18n from '@src/locales';
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'spare-statistics-dialog',
  props: {
    card:{
      type: Object,
      default: () => ({})
    },   
    // 导出数据， true 附加组件表单设置使用，false 选择导出列
    useExportUrl: {
      type: Boolean,
      default: true,
    }
  },
  data() {
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      fixedPrefixTaskPath:'',
      loading: false,
      visible: false,
      totalElements: 0,
      exportUrl: SettingTaskApi.taskPath,
      form: {
        cardId: '',
        inventoryTypeEnum: '',
        taskTimeTypeEnum:'success',
        pageNum: 1,
        pageSize: 10,
        startDate: '', 
        endDate: '',
        searchKey:''
      },
      tableData:[],
      cardFieldsData:[],
      timeArrRange:[],
      internationalGray,
      exportColumnList:[],
    };
  },
  filters: {
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm')
    }
  },
  computed: {
    /** 
    * @description 表头设置
    */
    columns() {
      let cardFields = this.cardFieldsData;
      if(cardFields.length > 0){
        return fieldUtil.packSpareFields(cardFields, this.form.inventoryTypeEnum)   
      }
    },
    exportColumn(){
      const eventInfo = {
        label: i18n.t('common.task.TaskExportGroupTextEnum.task'),
        value: 'task',
        columns: [],
      }

      const cardInfo = {
        label: i18n.t('task.AdditionalInformation'),
        value: 'card',
        columns: [],
      }

      for(let item of this.exportColumnList){
        item.export = true;
        item.label = item.displayName;
        item.field = item.fieldName;
        item.value = item.fieldName;

        if(item.tableName === 'task'){
          eventInfo.columns.push(item);
        }else if(item.tableName === 'card'){
          cardInfo.columns.push(item);
        }

      }
      let column = [eventInfo, cardInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });
      return column
    }
  },
  mounted() {
    this.timeRange();
  },
  methods: {
    // 选择导出 Start
    OpenExport(){
      this.$refs.exportRef.open();
    },
    getTaskCardExportFields(){
      SettingTaskApi.getTaskCardExportFields({
        cardId: this.card.id
      })
      .then(res=>{
        if(res.success){
          this.exportColumnList = res.result;
        }
      })
    },
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    exportCountCheck(ids, max){
      return null
    },
    disposeSubmitTime(){
      const [ startTime, endTime ] = this.timeArrRange || []
      return {
        startTime,
        endTime,
      }
    },
    exportParamsBuild(checkedMap, ids){
      const {card, task} = checkedMap

      const { form } = this
      const { taskNoStr, userNameStr } = form
      const params = {
        cardId: this.card.id,
        userNameStr,
        taskNoStr,
        inventoryTypeEnum: this.form.inventoryTypeEnum,
        taskTimeTypeEnum: this.form.taskTimeTypeEnum,
        ...this.disposeSubmitTime()
      }

      return {
        taskFields: task.join(','),
        cardFields: card.join(','),
        cardId: this.card.id,
        searchModel: JSON.stringify(params),
        total: this.totalElements
      }
    },
    fmt_synergies(value = []) {
      const arr = []
      value.length &&
        value.forEach(item => {
          arr.push(item.displayName)
        })
      return arr.length < 4
        ? arr.join('，')
        : this.$t('task.setting.taskAdditionalSetting.howManyUsers', {users: arr.join('，'), num: arr.count})
    },
    valueAtt_href(field) {
      return JSON.parse(field)
    },
    /** 
    * @description 默认时间
    */
    timeRange() {
      this.timeArrRange = [+nearDateBy(1, 'month'), +dayTimeEnd()];
      this.form.startDate = this.timeArrRange[0];
      this.form.endDate = this.timeArrRange[1];
    },

    onTimeChange(time) {
      this.form.startDate = time?.[0];
      this.form.endDate = time?.[1];
    },

    /** 
    * @description 查看工单详情
    */
    openTaskView(taskId, taskNo) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
        
      //   url: `/task/view/${taskId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        fromId
      })

    },
    /** 
    * @description 打开统计弹窗
    */
    openDialog() {
      this.visible = true;
      this.timeRange();
      
      if(this.card.id) {
        this.form.cardId = this.card.id;
        this.getCardFields()
        this.getCardCountReq();
        this.getTaskCardExportFields();
      }
    },
    onClose(form) {
      this.visible = false;
      this.timeArrRange = [];
      this.form = {
        cardId: '',
        inventoryTypeEnum: '',
        taskTimeTypeEnum:'success',
        pageNum: 1,
        pageSize: 10,
        startDate: '', 
        endDate: '',
        searchKey:''
      }
    },
    /** 
    * @description 搜索
    */
    onSearch() {
      this.getCardCountReq()
    },

    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.form.pageSize = pageSize;
      this.form.pageNum = 1;
      this.getCardCountReq();

    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jumpPage(pageNum) {
      this.form.pageNum = pageNum;
      this.getCardCountReq();
    },

    // 获取统计Fields列表
    getCardFields() {
      SettingTaskApi.getCardFields({cardId:this.card.id}).then(res=>{
        const { code, message, result = [] } = res;
        if( code == 0 ){
          this.cardFieldsData = result.filter(item=> item.formType !== FieldTypeMappingEnum.JsCodeBlock);
        }
      }).catch(error=>({}))
    },

    // 获取统计列表
    getCardCountReq() {
      SettingTaskApi.statisticalInventory(this.form).then(res=>{
        const { code, message, result } = res;
        this.loading = false;
        if(code == 0) {
          this.totalElements = result.total;
          this.tableData = result.list;
        }
        
      }).catch(error=>({ }))

    }
  },
};
</script>
<style lang="scss">
.statistical-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .base-modal-content{
      .statistical-search{
        display: flex;
        justify-content: space-between;
        .search-left{
          display: flex;
          justify-content: flex-start;
          .el-date-editor{
            margin-right: 12px;
            width: 256px !important;
          }
          .el-input{
            margin-right: 12px;
            width: 230px;
          }
        }
        .search-right{
          line-height: 32px;
          a{
            width: 58px;
            height: 32px;
           background: $color-primary-light-1;
            border-radius: 4px;
            border: 1px solid $color-primary-light-2;
            color: $color-primary-light-6;
            text-decoration: none;
            padding: 6px 10px;
          }
        }
      }
      .statistical-table{
        padding: 0;
        margin-top: 17px;  
        a{
          width: 100%;
          color: $color-primary-light-6;
          cursor: pointer;
          display: block;
          @include text-ellipsis();
        }
      }
      .table-footer{
        margin-top: 17px;
      }
      .el-table--border{
        border-bottom: 1px solid #ebeef5;
      }
    }
    

  }
  .ml-3 {
    margin-left: 3px;
  }
}
</style>